package com.lagou.client;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;
import org.apache.hadoop.hbase.util.Bytes;

import java.io.IOException;
import java.util.ArrayList;

public class UserRelation {

    String table = "user_relation";

    Configuration conf = null;
    Connection conn = null;

    public void init() throws IOException {
        conf = HBaseConfiguration.create();

        //配置hbase地址端口号
        conf.set("hbase.zookeeper.quorum", "linux121,linux122");
        conf.set("hbase.zookeeper.property.clientPort", "2181");

        conn = ConnectionFactory.createConnection(conf);
    }

    public void createTable() throws IOException {
        //获取HbaseAdmin对象用来建表
        HBaseAdmin admin = (HBaseAdmin) conn.getAdmin();
        //创建Htabledesc描述器，表描述器
        HTableDescriptor user_rel = new HTableDescriptor(TableName.valueOf(table));
        //制定烈族
        user_rel.addFamily(new HColumnDescriptor("friends"));
        admin.createTable(user_rel);
        System.out.println("用户关系表创建成功");
    }


    public void addFriend(String uid, String friendUid) throws IOException {
        Table userRel = conn.getTable(TableName.valueOf(table));
        Put put = new Put(Bytes.toBytes(uid));

        put.addColumn(Bytes.toBytes("friends"), Bytes.toBytes(friendUid), Bytes.toBytes(friendUid));
        userRel.put(put);
        userRel.close();
        System.out.println(uid + "添加好友<"+friendUid+">成功");
    }

    public void deleteFriend(String uid, String friendUid) throws IOException {
        Table userRel = conn.getTable(TableName.valueOf(table));
        ArrayList<Delete> deletes = new ArrayList<>();

        //删除好友
        Delete delete1 = new Delete(Bytes.toBytes(uid));
        delete1.addColumns(Bytes.toBytes("friends"), Bytes.toBytes(friendUid));
        deletes.add(delete1);

        //同时对方删除
        Delete delete2 = new Delete(Bytes.toBytes(friendUid));
        delete2.addColumns(Bytes.toBytes("friends"), Bytes.toBytes(uid));
        deletes.add(delete2);

        userRel.delete(deletes);
        userRel.close();
        System.out.println(uid + "删除好友<"+friendUid+">成功");
    }
}
